<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8" />
    <title>首页</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <link rel="stylesheet" href="mainpage.css" />
    <link rel="stylesheet" href="通用新页面css.css" />
</head>
<body>
<div id="app">
    <div class="container">
        <div class="sidebar">
            <a href="mainpage.html" class="sidebar-item active">首页</a>
            <a href="dish-management.html" class="sidebar-item">菜品管理</a>
            <a href="order-management.html" class="sidebar-item">订单管理</a>
            <a href="marketing-statistics.html" class="sidebar-item">营销统计</a>
            <a href="UserPage.html" class="sidebar-item">用户管理</a>
        </div>
        <div class="content">
            <!-- 欢迎横幅 -->
            <div class="welcome-banner">
                <h1>欢迎回来，管理员！</h1>
                <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
            </div>
            <!-- 数据概览 -->
            <h2 class="section-title">数据概览</h2>
            <div class="dashboard">
                <div class="stat-card">
                    <i class="fas fa-utensils"></i>
                    <div class="value">{{ stats.totalDishes }}</div>
                    <div class="label">菜品总数</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-shopping-bag"></i>
                    <div class="value">{{ stats.todayOrders }}</div>
                    <div class="label">今日订单</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-money-bill-wave"></i>
                    <div class="value">¥{{ stats.todayRevenue.toFixed(2) }}</div>
                    <div class="label">今日营收</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-user-check"></i> <!-- 今日活跃用户图标 -->
                    <div class="value">{{ stats.todayActiveUsers }}</div>
                    <div class="label">今日活跃用户</div>
                </div>
            </div>
            <!-- 快捷操作 -->
            <h2 class="section-title">快捷操作</h2>
            <div class="quick-actions">
                <div class="action-btn" @click="navigateTo('dish-management.html')">
                    <i class="fas fa-plus-circle"></i>
                    <span>新增菜品</span>
                </div>
                <div class="action-btn" @click="navigateTo('order-management.html')">
                    <i class="fas fa-clipboard-list"></i>
                    <span>处理订单</span>
                </div>
                <div class="action-btn" @click="navigateTo('UserPage.html')">
                    <i class="fas fa-bullhorn"></i>
                    <span>管理用户</span>
                </div>
                <div class="action-btn" @click="navigateTo('marketing-statistics.html')">
                    <i class="fas fa-chart-line"></i>
                    <span>查看报表</span>
                </div>
            </div>
            <!-- 最近订单 -->
            <h2 class="section-title">最近订单</h2>
            <div class="recent-orders">
                <div class="order-item" v-for="order in recentOrders" :key="order.id">
                    <div>
                        <div><strong>订单 #{{ order.orderNumber }}</strong></div>
                        <div>{{ order.buyer }} · {{ formatDateTime(order.createTime) }}</div>
                    </div>
                    <div>
                        <div class="order-status" :class="'status-' + getStatusClass(order.orderState)">
                            {{ getStatusText(order.orderState) }}
                        </div>
                        <div>¥{{ order.totalAmount.toFixed(2) }}</div>
                    </div>
                </div>
                <div v-if="recentOrders.length === 0" style="text-align: center; padding: 20px; color: #666;">
                    暂无最近订单
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    const { createApp, ref, onMounted } = Vue;
    createApp({
        setup() {
            // 日期格式化
            const currentDate = ref(new Date().toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            }));

            // 统计数据
            const stats = ref({
                totalDishes: 0,           // 菜品总数
                todayOrders: 0,           // 今日订单数
                todayRevenue: 0,          // 今日营收
                todayActiveUsers: 0       // 今日活跃用户（今日下单的唯一用户数）
            });

            // 最近订单
            const recentOrders = ref([]);
            // 今日日期（用于筛选今日订单）
            const today = ref(new Date().toISOString().split('T')[0]);

            // 1. 获取菜品总数（调用/dish/dishCount接口）
            const fetchDishCount = async () => {
                try {
                    const response = await axios.get('/dish/dishCount', {
                        headers: {
                            Authorization: "Bearer " + localStorage.getItem("food_token")
                        }
                    });
                    stats.value.totalDishes = response.data.data || 0;
                } catch (error) {
                    console.error("获取菜品总数失败:", error);
                    stats.value.totalDishes = 0;
                }
            };

            // 2. 获取订单数据（计算今日订单、营收、活跃用户和最近订单）
            const fetchOrderData = async () => {
                try {
                    const response = await axios.get('/t-order/currentMthOrd', {
                        headers: {
                            Authorization: "Bearer " + localStorage.getItem("food_token")
                        }
                    });

                    if (Array.isArray(response.data.data)) {
                        const allOrders = response.data.data;

                        // 筛选今日订单
                        const todayOrders = allOrders.filter(order =>
                            order.createTime?.split('T')[0] === today.value
                        );

                        // 计算今日活跃用户（按openid去重）
                        const uniqueUserIds = new Set();
                        todayOrders.forEach(order => {
                            if (order.id) uniqueUserIds.add(order.id);
                        });
                        stats.value.todayActiveUsers = uniqueUserIds.size;

                        // 计算今日订单数和营收
                        stats.value.todayOrders = todayOrders.length;
                        stats.value.todayRevenue = todayOrders.reduce(
                            (sum, order) => sum + Number(order.totalAmount), 0
                        );

                        // 获取最近5条订单（按创建时间倒序）
                        recentOrders.value = [...allOrders]
                            .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                            .slice(0, 5);
                    }
                } catch (error) {
                    console.error("获取订单数据失败:", error);
                }
            };

            // 订单状态文本映射（0-新单、1-已取消、2-已完成）
            const getStatusText = (state) => {
                const statusMap = { 0: '新单', 1: '已取消', 2: '已完成' };
                return statusMap[state] || '未知状态';
            };

            // 订单状态样式映射
            const getStatusClass = (state) => {
                const classMap = { 0: 'pending', 1: 'cancelled', 2: 'completed' };
                return classMap[state] || 'pending';
            };

            // 格式化日期时间（显示到分）
            const formatDateTime = (dateTime) => {
                return dateTime ? dateTime.replace('T', ' ').slice(0, 16) : '';
            };

            // 页面跳转
            const navigateTo = (page) => {
                window.location.href = page;
            };

            // 页面加载时初始化数据
            onMounted(() => {
                fetchDishCount();
                fetchOrderData();
            });

            return {
                currentDate,
                stats,
                recentOrders,
                getStatusText,
                getStatusClass,
                formatDateTime,
                navigateTo
            };
        }
    }).mount("#app");
</script>
</body>
</html>